import React, { useEffect, useReducer, useCallback } from 'react';
import { Card, Table } from 'antd';
import SearchForm from './SearchForm';

const useAsyncTable: React.FC<any> = (props) => {
  const { owncolumns, queryAction, params, baseProps } = props; // 列数据、请求数据接口、搜索数据、antd的基础props(table的其他属性)
  const searchList = owncolumns().filter(
    (item: any) => item.hasOwnProperty('hideInSearch') && !item.hideInSearch,
  );

  // 分页数据
  const paginationInitial: any = {
    current: 1,
    pageSize: 10,
    total: 0,
  };
  // table组件全量数据
  const initialState: any = {
    loading: false,
    pagination: paginationInitial,
    dataSource: [],
  };
  const reducer = (state: any, action: any) => {
    const { payload } = action;
    switch (action.type) {
      case 'TOGGLE_LOADING': //更改loading状态
        return { ...state, loading: !state.loading };
      case 'SET_PAGINATION': //设置分页数据
        return { ...state, pagination: payload.pagination };
      case 'SET_DATA_SOURCE': //设置远程数据源
        return { ...state, dataSource: payload.dataSource };
      default:
        return state;
    }
  };
  const [state, dispatch] = useReducer(reducer, initialState);

  // 改变页码
  function handleTableChange(payload: any) {
    if (payload) {
      const { current } = payload;
      dispatch({
        type: 'SET_PAGINATION',
        payload: {
          pagination: {
            ...state.pagination,
            current,
          },
        },
      });
    }
  }
  // useCallback包装请求，缓存依赖，优化组件性能
  const fetchDataWarp = useCallback(
    fetchData,
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [params, state.pagination.current, owncolumns, queryAction],
  );
  // 获取数据
  async function fetchData() {
    dispatch({
      type: 'TOGGLE_LOADING',
    });
    // 分页字段名称转换
    const { current, pageSize } = state.pagination;
    const res = await queryAction({ current, pageSize, ...params }).catch((err: any) => {
      console.log(err);
      dispatch({ type: 'TOGGLE_LOADING' });
      return {};
    });
    // 关闭loading
    dispatch({
      type: 'TOGGLE_LOADING',
    });
    if (res.data.length > 0) {
      // const { totalpageSize, list } = res
      dispatch({
        type: 'SET_PAGINATION',
        payload: {
          pagination: { ...state.pagination, total: res.meta.pagination.total },
        },
      });
      // 回填list数据
      dispatch({
        type: 'SET_DATA_SOURCE',
        payload: {
          dataSource: res.data,
        },
      });
    }
  }
  useEffect(() => {
    fetchDataWarp();
  }, [fetchDataWarp]);
  return (
    <div>
      <Card style={{ marginBottom: '20px' }}>
        <SearchForm searchList={searchList} />
      </Card>
      <Card>
        <Table
          columns={owncolumns(fetchData)}
          pagination={state.pagination}
          dataSource={state.dataSource}
          loading={state.loading}
          onChange={handleTableChange}
          {...baseProps}
        />
      </Card>
    </div>
  );
};
export default useAsyncTable;
